package com.tianjipms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianjipms.entity.Bill;
import com.tianjipms.service.AccountService;
import com.tianjipms.service.BillService;
import com.tianjipms.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/api/bill")
public class BillController {
    @Resource
    private BillService billService;
    @Resource
    private AccountService accountService;
    //生成账单
//    @PostMapping("/add")
//    public Result addBill(Bill bill){
//        bill.setCreateTime(new Date());
//        bill.setStatus(0);
//        return Result.ok(billService.save(bill));
//    }

    //按id分页查询账单
    @GetMapping("/list")
    public Result listByUserId(@RequestParam("userId") Long userId,
                               @RequestParam(defaultValue = "1") Long pageNum,
                               @RequestParam(defaultValue = "5") Long pageSize){
        IPage<Bill> page = new Page<>(pageNum, pageSize);
        billService.findBillListByPage(page,userId);
        return Result.ok(page);
    }
    //完成账单
    @PostMapping("/finish")
    public Result finishBill(@RequestBody Bill bill){
        Bill newBill = billService.getById(bill.getId());
        //付钱
        Result result =accountService.updatePriceByUserId(newBill,true);
        if (result.getSuccess()){
            newBill.setStatus(1);
            newBill.setFinishTime(new Date());
            billService.updateById(newBill);
            return accountService.updatePriceByUserId(newBill,false);
        }
        return result;
    }
}
